package com.huangd.platform.config;

import com.huangd.platform.common.utils.Utils;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

public class MQUtils {

	public static ConnectionFactory createConnectFactory(String host, int port, String username, String password) throws Exception {
		return createConnectFactory(host, port, username, password, null, port == ConnectionFactory.DEFAULT_AMQP_OVER_SSL_PORT);
	}

	public static ConnectionFactory createConnectFactory(String host, int port, String username, String password, String virtualHost, boolean ssl) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(host);
		factory.setPort(port);
		factory.setUsername(username);
		factory.setPassword(password);

		if (Utils.notEmpty(virtualHost)) {
			factory.setVirtualHost(virtualHost);
		} else {
			factory.setVirtualHost("/");
		}

		if (ssl)
			factory.useSslProtocol();

		return factory;
	}

	public static Connection createConnection(String host, int port, String username, String password) throws Exception {
		return createConnection(host, port, username, password, null, port == ConnectionFactory.DEFAULT_AMQP_OVER_SSL_PORT, null);
	}

	public static Connection createConnection(String host, int port, String username, String password, String virtualHost, boolean ssl) throws Exception {
		return createConnection(host, port, username, password, virtualHost, ssl, null);
	}

	public static Connection createConnection(String host, int port, String username, String password, String virtualHost, boolean ssl, String connectionName) throws Exception {
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost(host);
		factory.setPort(port);
		factory.setUsername(username);
		factory.setPassword(password);

		if (Utils.notEmpty(virtualHost)) {
			factory.setVirtualHost(virtualHost);
		} else {
			factory.setVirtualHost("/");
		}

		if (ssl)
			factory.useSslProtocol();

		Connection connection = factory.newConnection(connectionName);
		return connection;
	}
}
